// components/SidebarMenu.tsx
'use client'

import { useEffect, useMemo, useState } from 'react'
import { Button, Menu } from 'antd'
import type { MenuProps } from 'antd'
import { useRouter, usePathname } from 'next/navigation'
import { createKeyParentMap, extractAllKeys, findMatchedKey } from '@/lib/menu-utils'
import { AppstoreOutlined, MailOutlined, MenuFoldOutlined, MenuUnfoldOutlined, SettingOutlined } from '@ant-design/icons'

type Props = {
    menuItems?: MenuProps['items']
}

const Items: MenuProps['items'] = [
    {
        key: '/dashboard',
        icon: <MailOutlined />,
        label: '仪表盘',
    },
    {
        key: '/buy',
        icon: <AppstoreOutlined />,
        label: '内容管理',
        children: [
        {
                key: '/user',
                label: '用户',
            },
            {
                key: '/food',
                label: '美食',
            },
            {
                key: '/clothes',
                label: '衣物',
            },
            {
                key: '/vagetable',
                label: '蔬菜',
                children: [
                    {
                        key: '/leaf',
                        label: '叶子菜',
                    },
                    {
                        key: '/root',
                        label: '根茎菜',
                    },
                ],
            },
        ],
    },
    {
        key: '/setting',
        icon: <SettingOutlined />,
        label: '设置',
        children: [
            {
                key: '/profile',
                label: '个人中心',
            },
            {
                key: '/about',
                label: '关于我们',
            }
        ],
    },
]
export default function SidebarMenu({ menuItems = Items }: Props) {
    const router = useRouter()
    const pathname = usePathname()

    const [selectedKeys, setSelectedKeys] = useState<string[]>([])
    const [openKeys, setOpenKeys] = useState<string[]>([])
    const [collapsed, setCollapsed] = useState<boolean>(false)
    // 新增：控制是否完成客户端初始化（解决SSR/CSR样式不匹配）
    const [isClientReady, setIsClientReady] = useState(false);
    // 所有菜单 key
    const allKeys = useMemo(() => extractAllKeys(menuItems), [menuItems])
    // key => 父 key 映射
    const parentMap = useMemo(() => createKeyParentMap(menuItems), [menuItems])
    // 顶层菜单 key
    const rootKeys = useMemo(
        () => menuItems?.map(item => item?.key).filter(Boolean) as string[],
        [menuItems]
    )

    // 根据路由更新选中项与展开项
    useEffect(() => {
        const matchedKey = findMatchedKey(pathname, allKeys)
        setSelectedKeys(matchedKey ? [matchedKey] : [])

        // 展开父级菜单
        const parents: string[] = []
        let current = matchedKey
        while (current && parentMap[current]) {
            parents.push(parentMap[current])
            current = parentMap[current]
        }
        setOpenKeys(parents)
    }, [pathname, allKeys, parentMap])

    // 客户端渲染完成后再启用动画（避免初始挤压）
    useEffect(() => {
        setIsClientReady(true);
    }, []);
    if (!isClientReady) return null

    const onOpenChange = (keys: string[]) => {
        const latest = keys.find(k => !openKeys.includes(k))
        if (latest && rootKeys.includes(latest)) {
            setOpenKeys([latest]) // 只展开一个同级菜单
        } else {
            setOpenKeys(keys)
        }
    }

    const onClick = ({ key }: { key: string }) => {
        router.push(key)
    }

    return (

        <div className={`${!collapsed ? 'w-64 md:w-42' : 'w-16'} transition-all duration-300`}>
            {/* 收缩/展开按钮 */}
            <Button
                type="text"
                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                onClick={() => setCollapsed(!collapsed)}
                className={`
          mb-2 w-full justify-center  // 按钮占满宽度，居中显示
          text-gray-300 hover:text-white  // 自定义hover效果
          ${!collapsed ? 'px-4' : 'px-0'}  // 展开状态增加左右内边距
        `}
            />
            <Menu
                mode="inline"
                theme="light"
                inlineCollapsed={collapsed}
                selectedKeys={selectedKeys}
                openKeys={collapsed ? [] : openKeys}
                onOpenChange={onOpenChange}
                onClick={onClick}
                items={menuItems}
                className={`h-[calc(100vh-40px)]  // 减去按钮高度，避免溢出
                  transition-all 
                  ${isClientReady ? 'transition-all duration-300' : ''}`} // 客户端就绪后才启用动画"
            />

        </div>
    )
}